<template>
  <div class="dhcc-body">
    <el-row :gutter="10">
      <el-col :span="4">
        <div class="dhcc-tree" style="height: 650px">
          <!-- 树形数据 -->
          <el-tree
            :data="data"
            :props="defaultProps"
            highlight-current
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            node-key="orgKey"
            :default-expanded-keys="['ROOT']"
          ></el-tree>
        </div>
      </el-col>
      <el-col :span="20">
        <div class="dhcc-search">
          <!-- 检索区 -->
          <el-form
            ref="searchForm"
            :model="searchMap"
            class="demo-form-inline"
            size="mini"
            :inline="true"
          >
            <el-form-item prop="orgName">
              <el-input
                v-model="searchMap.orgName"
                placeholder="机构名称"
              ></el-input>
            </el-form-item>
            <el-form-item prop="activeFlg">
              <el-radio-group
                v-model="searchMap.activeFlg"
                @change="chageStatus"
              >
                <el-radio label="1">启用</el-radio>
                <el-radio label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="fetchData" icon="el-icon-search"
                >查询</el-button
              >
              <el-button type="primary" @click="handleAdd" icon="el-icon-plus"
                >新建</el-button
              >
              <el-button @click="resetForm('searchForm')" icon="el-icon-refresh"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="dhcc-main">
          <!-- 表格数据 -->
          <el-table
            :data="list"
            height="550"
            border
            style="width: 100%"
            size="mini"
          >
            <el-table-column
              type="index"
              label="序号"
              width="60"
            ></el-table-column>
            <el-table-column
              prop="orgKey"
              label="机构代码"
              width="80"
            ></el-table-column>
            <el-table-column
              prop="orgName"
              label="机构名称"
              width="250"
            ></el-table-column>
            <el-table-column
              prop="orgTypeDesc"
              label="机构类型"
              width="150"
            ></el-table-column>
            <el-table-column prop="parentOrgName" label="上级机构">
            </el-table-column>
            <el-table-column
              prop="expiryDate"
              label="截止时间"
              width="100"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="activeFlg"
              label="状态"
              width="80"
              align="center"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.activeFlg | statusFilter }}</span>
              </template>
            </el-table-column>
            <el-table-column label="启用/停用" width="80" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="warning"
                  @click="
                    handleIsDisplay(scope.row.orgKey, scope.row.activeFlg)
                  "
                  >{{ scope.row.activeFlg == 1 ? "停用" : "启用" }}</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" align="center">
              <template slot-scope="scope">
                <el-button size="mini" @click="handleEdit(scope.row.orgKey)"
                  >编辑</el-button
                >
                <el-button
                  type="success"
                  size="mini"
                  @click="handlePagePath(scope.row.orgKey)"
                  >菜单</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-col>
    </el-row>
    <!-- 弹出新增窗口 -->
    <el-dialog
      title="机构信息编辑"
      :visible.sync="dialogFormVisible"
      width="900px"
    >
      <el-form
        ref="pojoForm"
        :rules="rules"
        label-width="100px"
        label-position="right"
        :model="pojo"
        size="mini"
        style="width: 800px"
        class="demo-form-inline"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="机构代码" prop="orgKey">
              <el-input
                v-model="pojo.orgKey"
                :disabled="saveFlg"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="机构名称" prop="orgName">
              <el-input
                v-model="pojo.orgName"
                @blur="handleBlur"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="机构简称" prop="orgShortName">
              <el-input v-model="pojo.orgShortName"></el-input> </el-form-item
          ></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="简拼" prop="py">
              <el-input v-model="pojo.py"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="机构类型" prop="orgType">
              <el-select v-model="pojo.orgType" filterable style="width: 100%">
                <el-option
                  v-for="option in orgTypeList"
                  :key="option.code"
                  :label="option.text"
                  :value="option.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="机构等级" prop="orgLevel">
              <el-select v-model="pojo.orgLevel" filterable style="width: 100%">
                <el-option
                  v-for="option in orgLevelList"
                  :key="option.code"
                  :label="option.text"
                  :value="option.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="顺序号" prop="seqNo">
              <el-input v-model="pojo.seqNo" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="执照编码" prop="licenceCode">
              <el-input v-model="pojo.licenceCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="门诊业务">
              <el-switch
                v-model="pojo.businessScopeO"
                active-value="1"
                inactive-value="0"
              ></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="住院业务">
              <el-switch
                v-model="pojo.businessScopeI"
                active-value="1"
                inactive-value="0"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="所在省" prop="province">
              <el-select
                v-model="pojo.province"
                filterable
                style="width: 100%"
                @change="changeProvince"
              >
                <el-option
                  v-for="option in provinceList"
                  :key="option.cityCode"
                  :label="option.cityName"
                  :value="option.cityCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所在市" prop="city">
              <el-select
                v-model="pojo.city"
                filterable
                style="width: 100%"
                @change="changeCity"
              >
                <el-option
                  v-for="option in cityList"
                  :key="option.cityCode"
                  :label="option.cityName"
                  :value="option.cityCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所在区" prop="area">
              <el-select
                v-model="pojo.area"
                filterable
                style="width: 100%"
                ref="getArea"
              >
                <el-option
                  v-for="option in areaList"
                  :key="option.cityCode"
                  :label="option.cityName"
                  :value="option.cityCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="邮政编码" prop="postcode">
              <el-input v-model="pojo.postcode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="管理公司">
              <el-switch
                v-model="pojo.manageFlg"
                @change="changeManage"
                active-value="1"
                inactive-value="0"
              ></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上级机构" prop="parentOrgKey">
              <el-select
                v-model="pojo.parentOrgKey"
                filterable
                style="width: 100%"
                :disabled="parentOrgDisabled"
              >
                <el-option
                  v-for="option in manageList"
                  :key="option.orgKey"
                  :label="option.orgName"
                  :value="option.orgKey"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="截止日期" prop="expiryDate">
              <el-date-picker
                v-model="pojo.expiryDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                format="yyyy-MM-dd"
                value-format="yyyyMMddHHmmss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="限定用户" prop="limitedNumber">
              <el-input v-model="pojo.limitedNumber" type="number"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="pojo.address"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="机构简介" prop="synopsis">
              <el-input
                type="textarea"
                :rows="3"
                placeholder=""
                v-model="pojo.synopsis"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="mini"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="!saveFlg ? addData('pojoForm') : updateData('pojoForm')"
          size="mini"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 弹出新增窗口 -->
    <el-dialog
      title="机构菜单信息"
      :visible.sync="dialogPathFormVisible"
      width="450px"
    >
      <el-form
        ref="pojoPathForm"
        :rules="rules"
        :model="pojo"
        size="mini"
        style="width: 400px"
        class="demo-form-inline"
      >
        <el-form-item prop="pathTree">
          <el-tree
            :data="pathTree"
            show-checkbox
            default-expand-all
            node-key="id"
            ref="tree"
            highlight-current
            :props="defaultPathProps"
            :check-strictly="checkStrictly"
            style="height: 450px; overflow: auto"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPathFormVisible = false" size="mini"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="updatePathData('pojoPathForm')"
          size="mini"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  orgTree,
  search,
  add,
  getById,
  update,
  updateStatus,
  selectManageList,
  getOrgPath,
  updateOrgPath,
} from "@/api/sys/sysHospital";
import { selectList as dictSelect } from "@/api/sys/sysDictionary";
import { selectList as citySelect } from "@/api/sys/sysCity";
import { getList } from "@/api/sys/sysPagePath";
import store from "@/store/index";
import vPinyin from "@/utils/py";

// 状态类型
const statusOptions = [
  { type: 0, name: "停用" },
  { type: 1, name: "启用" },
];

// 管理机构
const manageOptions = [
  { type: 0, name: "否" },
  { type: 1, name: "是" },
];

export default {
  name: "sysHospital",
  data() {
    return {
      list: [],
      total: 0, // 总记录数
      currentPage: 1, // 当前页, 默认第1页
      pageSize: 10, // 每页显示条数， 10条
      data: [],
      defaultProps: {
        id: "orgKey",
        children: "children",
        label: "orgName",
      }, // 树形结构
      defaultPathProps: {
        id: "id",
        children: "children",
        label: "name",
        type: "type",
      }, // 树形结构
      pathTree: [],
      checkStrictly: false,
      selectOrgKey: null,
      searchMap: {
        parentOrgKey: "",
        orgName: "",
        activeFlg: "1",
      }, // 条件查询绑定条件值
      pojo: {
        orgKey: "",
        orgName: "",
        orgShortName: "",
        py: "",
        orgType: "",
        orgLevel: "",
        seqNo: 0,
        licenceCode: "",
        province: "",
        city: "",
        area: "",
        address: "",
        postcode: "",
        phoneNumber: "",
        synopsis: "",
        businessScopeO: "0",
        businessScopeI: "0",
        manageFlg: "0",
        parentOrgKey: "",
        expiryDate: "",
        limitedNumber: 100,
        createUserKey: store.state.user.userKey,
      }, // 提交的数据
      saveFlg: false, // 新增/更新状态 false: 新增； true：更新
      dialogFormVisible: false, // 控制对话框
      dialogPathFormVisible: false, // 控制菜单对话框
      statusOptions: statusOptions, // 状态类型
      manageOptions: manageOptions, // 管理机构
      manageList: [], // 管理机构列表
      orgTypeList: [], // 机构类型列表
      orgLevelList: [], // 机构等级列表
      provMap: {
        cityCode: "",
        cityLevel: 1,
      },
      cityMap: {
        cityCode: "",
        cityLevel: 2,
      },
      areaMap: {
        cityCode: "",
        cityLevel: 3,
      },
      provinceList: [], // 所在省
      cityList: [], // 所在市
      cityAllList: [], // 所在市(全部)
      areaList: [], // 所在区
      areaAllList: [], // 所在区(全部)
      parentOrgDisabled: true,
      rules: {
        // 校验规则
        orgKey: [
          {
            required: true,
            message: "机构代码不能为空",
            trigger: "blur",
          },
        ],
        orgName: [
          {
            required: true,
            message: "机构名称不能为空",
            trigger: "blur",
          },
        ],
        limitedNumber: [
          {
            required: true,
            message: "限定用户数不能为空",
            trigger: "blur",
          },
        ],
        expiryDate: [
          {
            required: true,
            message: "截止日期不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.fetchData();
    this.dataSelect();
  },
  methods: {
    // 查询功能
    fetchData() {
      orgTree().then((response) => {
        const resp = response;
        if (resp.flag) {
          this.data = response.data;
        } else {
          // 查询失败
          this.$message({ message: resp.message, type: "warning" });
        }
      });
      getList().then((response) => {
        const resp = response;
        if (resp.flag) {
          this.pathTree = response.data;
        } else {
          // 查询失败
          this.$message({ message: resp.message, type: "warning" });
        }
      });
    },
    // 列表数据
    dataSelect() {
      //机构类型
      dictSelect("OrgType").then((response) => {
        const resp = response;
        if (resp.flag) {
          this.orgTypeList = response.data;
        } else {
          // 查询失败
          this.$message({ message: resp.message, type: "warning" });
        }
      });
      //机构等级
      dictSelect("OrgLevel").then((response) => {
        const resp = response;
        if (resp.flag) {
          this.orgLevelList = response.data;
        } else {
          // 查询失败
          this.$message({ message: resp.message, type: "warning" });
        }
      });
      // 所在省
      citySelect(this.provMap).then((response) => {
        const resp = response;
        if (resp.flag) {
          this.provinceList = response.data;
        } else {
          // 查询失败
          this.$message({ message: resp.message, type: "warning" });
        }
      });
      // 所在市
      citySelect(this.cityMap).then((response) => {
        const resp = response;
        if (resp.flag) {
          this.cityAllList = response.data;
        } else {
          // 查询失败
          this.$message({ message: resp.message, type: "warning" });
        }
      });
      // 所在县
      citySelect(this.areaMap).then((response) => {
        const resp = response;
        if (resp.flag) {
          this.areaAllList = response.data;
        } else {
          // 查询失败
          this.$message({ message: resp.message, type: "warning" });
        }
      });
      // 上级机构
      selectManageList().then((response) => {
        const resp = response;
        if (resp.flag) {
          this.manageList = response.data;
        } else {
          // 查询失败
          this.$message({ message: resp.message, type: "warning" });
        }
      });
    },
    // 查询机构子集合数据
    handleNodeClick(data) {
      this.searchMap.parentOrgKey = data.orgKey;
      this.searchData(this.searchMap);
    },
    // 当每页条数改变后触发
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },
    // 当页码改变后触发
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    // 重置功能
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 启用/停用按钮
    handleIsDisplay(id, status) {
      this.$confirm(
        status === 1 ? "确认停用这条记录吗?" : "确认启用这条记录吗?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          // 确认
          updateStatus(id, status).then((response) => {
            const resp = response;
            if (resp.flag) {
              // 更新成功, 刷新列表数据
              this.fetchData();
              this.searchData(this.searchMap);
              this.$message({ message: resp.message, type: "success" });
            } else {
              // 更新失败
              this.$message({ message: resp.message, type: "warning" });
            }
          });
        })
        .catch(() => {
          // 取消
        });
    },
    // 切换状态按钮
    chageStatus() {
      this.fetchData();
    },
    // 查询数据
    searchData(map) {
      search(this.currentPage, this.pageSize, map).then((response) => {
        const reqs = response;
        this.total = reqs.data.total;
        this.list = reqs.data.rows;
      });
    },

    // 弹出新增窗口
    handleAdd() {
      this.dialogFormVisible = true;
      this.saveFlg = false;
      this.cityList = [];
      this.areaList = [];
      this.$nextTick(() => {
        // 异步事件
        this.$refs["pojoForm"].resetFields();
        this.pojo.orgKey = null;
        this.pojo.businessScopeO = "0";
        this.pojo.businessScopeI = "0";
        this.pojo.manageFlg = "0";
        this.parentOrgDisabled = true;
        this.pojo.province = "";
        this.pojo.city = "";
        this.pojo.area = "";
      });
    },
    // 变更所在省
    changeProvince() {
      this.cityList = [];
      this.areaList = [];
      this.pojo.city = "";
      this.pojo.area = "";
      // 查询所在市
      this.selectCity();
    },
    // 查询所在市
    selectCity() {
      if (this.pojo.province == "") {
        return;
      }
      for (let i = 0; i < this.cityAllList.length; i++) {
        if (
          this.pojo.province.substr(0, 3) ==
          this.cityAllList[i].cityCode.substr(0, 3)
        ) {
          this.cityList.push(this.cityAllList[i]);
        }
      }
    },
    // 变更所在市
    changeCity() {
      this.pojo.area = "";
      this.areaList = [];
      // 编辑时赋值
      // this.$nextTick(() => {
      //   //console.log("----------" + );
      //   this.$refs.getArea.selectedLabel = "南开区";
      //   this.pojo.area = "120104";
      // });
      // 查询所在县
      this.selectArea();
    },
    // 查询所在县
    selectArea() {
      if (this.pojo.city == "") {
        return;
      }
      for (let i = 0; i < this.areaAllList.length; i++) {
        if (
          this.pojo.city.substr(0, 4) ==
          this.areaAllList[i].cityCode.substr(0, 4)
        ) {
          this.areaList.push(this.areaAllList[i]);
        }
      }
    },
    // 变更管理公司
    changeManage() {
      if (this.pojo.manageFlg == 1) {
        this.parentOrgDisabled = false;
      } else {
        this.pojo.parentOrgKey = "";
        this.parentOrgDisabled = true;
      }
    },
    // 生成拼音
    handleBlur() {
      this.pojo.py = vPinyin.getFirstLettersUpper(this.pojo.orgName);
    },
    // 新增数据
    addData(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          add(this.pojo).then((response) => {
            const resp = response;
            if (resp.flag) {
              // 新增成功, 刷新列表数据
              this.fetchData();
              this.searchData(this.searchMap);
              this.dialogFormVisible = false; //关闭窗口
              this.$message({ message: resp.message, type: "success" });
            } else {
              // 新增失败
              this.$message({ message: resp.message, type: "warning" });
            }
          });
        } else {
          return false;
        }
      });
    },
    // 打开编辑窗口
    handleEdit(id) {
      this.handleAdd();
      this.saveFlg = true;
      getById(id).then((response) => {
        const resp = response;
        if (resp.flag) {
          this.pojo = resp.data;
          if (this.pojo.businessScopeO == 0) {
            this.pojo.businessScopeO = "0";
          } else {
            this.pojo.businessScopeO = "1";
          }
          if (this.pojo.businessScopeI == 0) {
            this.pojo.businessScopeI = "0";
          } else {
            this.pojo.businessScopeI = "1";
          }
          if (this.pojo.manageFlg == 0) {
            this.pojo.manageFlg = "0";
            this.parentOrgDisabled = true;
          } else {
            this.pojo.manageFlg = "1";
            this.parentOrgDisabled = false;
          }
          // 查询所在市
          this.selectCity();
          // 查询所在县
          this.selectArea();
        } else {
          this.$message({ message: resp.message, type: "warning" });
        }
      });
    },
    // 提交更新数据
    updateData(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          update(this.pojo).then((response) => {
            const resp = response;
            if (resp.flag) {
              // 更新成功, 刷新列表数据
              this.fetchData();
              this.searchData(this.searchMap);
              this.dialogFormVisible = false; //关闭窗口
              this.$message({ message: resp.message, type: "success" });
            } else {
              this.$message({ message: resp.message, type: "warning" });
              // 更新失败
            }
          });
        } else {
          return false;
        }
      });
    },
    // 弹出菜单窗口
    handlePagePath(id) {
      this.dialogPathFormVisible = true;
      this.checkStrictly = true;
      this.selectOrgKey = id;
      this.$nextTick(() => {
        // 异步事件
        this.$refs["pojoPathForm"].resetFields();
        this.$refs.tree.setCheckedKeys([]);
      });
      // 查询机构程序权限
      getOrgPath(id).then((response) => {
        const resp = response;
        if (resp.flag) {
          this.$refs.tree.setCheckedNodes(resp.data);
        } else {
          this.$message({ message: resp.message, type: "warning" });
        }
        this.checkStrictly = false;
      });
    },
    // 更新机构程序权限
    updatePathData(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updateOrgPath(
            this.selectOrgKey,
            this.$refs.tree
              .getCheckedNodes()
              .concat(this.$refs.tree.getHalfCheckedNodes())
          ).then((response) => {
            const resp = response;
            if (resp.flag) {
              // 更新成功, 刷新列表数据
              this.dialogPathFormVisible = false; //关闭窗口
              this.$message({ message: resp.message, type: "success" });
            } else {
              this.$message({ message: resp.message, type: "warning" });
              // 更新失败
            }
          });
        } else {
          return false;
        }
      });
    },
  },
  filters: {
    statusFilter(type) {
      // 全局的 statusOptions , 返回一个满足条件的对象
      const obj = statusOptions.find((obj) => obj.type === type);
      // 非空返回类型名称
      return obj ? obj.name : null;
    },
  },
};
</script>

<style>
</style>